<template>
  <div>
    <h2>新闻资讯编辑</h2>
    <br>
    <el-form :model="dataForm" ref="dataForm" @keyup.enter.native="dataFormSubmit" label-width="120px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="dataForm.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="副标题" prop="subtitle">
        <el-input v-model="dataForm.subtitle" placeholder="请输入副标题"></el-input>
      </el-form-item>
      <div style="overflow: hidden;">
        <el-form-item label="新闻类型" prop="newsTypeName" style="width: 50%;float: left;">
          <el-select :value="dataForm.newsTypeName" placeholder="请选择新闻类型" @change="newsTypeChange" style="width: 100%;">
            <el-option v-for="item,index in newsTypeArr" :key="index" :value="`${item.id}&${item.typeName}&${item.typeAliases}`">{{ item.typeName }}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="相关案例类型" prop="caseTypeName" style="width: 50%;float: left;">
          <el-select :value="dataForm.caseTypeName" placeholder="请选择相关案例类型" @change="caseTypeChange" style="width: 100%;">
            <el-option v-for="item,index in caseTypeArr" :key="index" :value="`${item.typeName}&${item.typeAliases}`">{{ item.typeName }}</el-option>
          </el-select>
        </el-form-item>
      </div>
      <el-form-item label="封面图" prop="images">
        <el-upload
          class="uploader"
          :action="uploaderUrl"
          :show-file-list="false"
          :on-success="handleUploaderSuccess"
          :before-upload="beforeUploaderUpload">
          <img v-if="dataForm.images" :src="dataForm.images" class="img" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <q class="notice">注：请上传 300px * 224px 图片</q>
      </el-form-item>
      <div style="display: flex;">
        <label class="el-form-item__label" style="width: 120px;">新闻资讯内容</label>
        <div style="flex: 1;">
          <script :id="ueId" class="ueditor-box" type="text/plain" style="width: 100%; height: 450px;"></script>
        </div>
      </div>
    </el-form>
    <br>
    <div style="display: flex;">
      <label class="el-form-item__label" style="width: 120px;"></label>
      <div style="flex: 1;">
        <el-button @click="$router.go(-1)">返回</el-button>
        <el-button type="primary" @click="dataFormSubmit" :disabled="dataFormDisabled">确定</el-button>
      </div>
    </div>
  </div>
</template>

<script>
  import ueditor from 'ueditor'
  export default {
    data () {
      return {
        uploaderUrl: this.$http.adornUrl('/api/v1/cms/file/uploadImg'),
        ue: null,
        ueId: `J_ueditorBox_${new Date().getTime()}`,
        newsTypeArr: [],
        caseTypeArr: [],
        dataFormDisabled: false,
        dataForm: {
          id: '',
          title: '',
          subtitle: '',
          newsType: '',
          newsTypeName: '',
          newsTypeAliases: '',
          caseTypeName: '',
          caseTypeAliases: '',
          images: '',
          content: ''
        }
      }
    },
    mounted () {
      this.ue = ueditor.getEditor(this.ueId, {
        serverUrl: this.$http.adornUrl('/api/v1/cms/ueditor/config'), // 服务器统一请求接口路径
        toolbars: [
          ['bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', '|', 'rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|', 'link', 'unlink', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|', 'insertimage', 'emotion', 'insertvideo', 'insertcode', 'template', '|', 'horizontal', 'date', 'time', 'spechars', '|', 'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols']
        ]
      })
      this.getNewsType()
      this.getCaseType()
      this.init()
    },
    methods: {
      // 回显新闻资讯
      init () {
        this.$http({
          url: this.$http.adornUrl('/api/v1/cms/news/queryNewsById'),
          method: 'POST',
          data: this.$http.adornParams({
            id: this.$route.query.id
          })
        }).then(({ data }) => {
          if (data.code === 200) {
            this.dataForm.id = data.data.id
            this.dataForm.title = data.data.title
            this.dataForm.subtitle = data.data.subtitle
            this.dataForm.newsType = data.data.newsType
            this.dataForm.newsTypeName = data.data.newsTypeName
            this.dataForm.newsTypeAliases = data.data.newsTypeAliases
            this.dataForm.caseTypeName = data.data.caseTypeName
            this.dataForm.caseTypeAliases = data.data.caseTypeAliases
            this.dataForm.images = data.data.images
            this.dataForm.content = data.data.content
            this.ue.ready(() => {
              this.ue.setContent(data.data.content)
            })
          }
        })
      },
      // 获取新闻类型
      getNewsType () {
        this.$http({
          url: this.$http.adornUrl('/api/v1/cms/newsType/queryNewsTypeList'),
          method: 'POST',
          data: this.$http.adornParams({
            pageNum: 1,
            pageSize: 50
          })
        }).then(({data}) => {
          if (data.code === 200) {
            this.newsTypeArr = data.data.list
          }
        })
      },
      // 选择新闻类型
      newsTypeChange (e) {
        if (e) {
          this.dataForm.newsType = e.split('&')[0]
          this.dataForm.newsTypeName = e.split('&')[1]
          this.dataForm.newsTypeAliases = e.split('&')[2]
        }
      },
      // 获取相关案例类型
      getCaseType () {
        this.$http({
          url: this.$http.adornUrl('/api/v1/cms/customerCaseType/queryCustomerCaseTypeList'),
          method: 'POST',
          data: this.$http.adornParams({
            pageNum: 1,
            pageSize: 50
          })
        }).then(({data}) => {
          if (data.code === 200) {
            this.caseTypeArr = data.data.list
          }
        })
      },
      // 选择相关案例类型
      caseTypeChange (e) {
        if (e) {
          this.dataForm.caseTypeName = e.split('&')[0]
          this.dataForm.caseTypeAliases = e.split('&')[1]
        }
      },
      // 上传前
      beforeUploaderUpload (file) {
        if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
          this.$message({
            message: '请上传图片文件',
            type: 'warning'
          })
          return false
        }
      },
      // 上传成功
      handleUploaderSuccess (res) {
        if (res.code !== 200) {
          this.$message({
            message: res.msg,
            type: 'error'
          })
          return false
        }
        this.dataForm.images = res.data
      },
      // 表单提交
      dataFormSubmit () {
        this.ue.ready(() => {
          this.dataForm.content = this.ue.getContent()
        })
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.dataFormDisabled = true
            this.$http({
              url: this.$http.adornUrl(`/api/v1/cms/news/${this.dataForm.id ? 'updateNews' : 'addNews'}`),
              method: 'POST',
              data: this.$http.adornParams(this.dataForm)
            }).then(({data}) => {
              if (data && data.code === 200) {
                this.$message({
                  message: data.msg,
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.$router.go(-1)
                    this.dataFormDisabled = false
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
<style>
  .uploader .el-upload {width: 300px;height: 224px;border: 1px dashed #dcdfe6;display: flex;align-items: center;justify-content: center;border-radius: 4px;overflow: hidden;transition: .2s;}
  .uploader .el-upload:hover {border-color: #c0c4cc;transition: .2s;}
  .uploader .el-upload:focus {border-color: #17B3A3;transition: .2s;}
  .uploader .el-upload .img {width: 100%;height: 100%;background-color: #f1f4f5;}
  .uploader~.notice {font-size: 12px;color:#999;}
</style>